#!/bin/env python
#-*- coding:utf-8 -*-

#----------------------------------------------------------------------------
# Name     :      mysqlrequest.py
# Purpose  :      mysql request handler
# Author   :      Albert cheng
# Created  :      2012-10-29
# Copyright:     (c) 2012 by Albertcheng
# Licence  :      wxWindows license
#----------------------------------------------------------------------------
import wx          
import sys
wx.SetDefaultPyEncoding("utf-8")
from dbo import *



class request_sqlite(sdbo):
    def __init__(self,log):
        self.Log = log
        sdbo.__init__(self)

class request_xml:
    def __init__(self,log):
        self.xml = ""
        self.Log = log
        self.config = "config//config.xml"
        self.new_config = "config//config_new.xml"
        
        
    def read_cfg(self):
        root = etree.parse(self.config).getroot()
        projs = root.getchildren()
        data = {}
        for proj in projs:
            dbs = proj.getchildren()
            if not data.has_key(proj.tag):
                data[proj.tag] = {}
            for ndb in dbs:
                if data[proj.tag].has_key("database"):
                    data[proj.tag]["database"].append(ndb.tag)
                else:
                    data[proj.tag]["database"] = [ndb.tag,]
                data[proj.tag]["attrib"] = ndb.items()
                tbs = ndb.getchildren()
                for ntb in tbs:
                    data[proj.tag][ntb.tag] = {}
                    data[proj.tag][ntb.tag]["attrib"] = ntb.attrib
                    cols = ntb.getchildren()
                    for ncol in cols:
                        data[proj.tag][ntb.tag][ncol.attrib["tag"]] = {}
                        data[proj.tag][ntb.tag][ncol.attrib["tag"]]["attrib"] = ncol.attrib
        return data
        
        
        
        
    def write_cfg(self,data):
        
        def __inner(data,parent):
            def _set_col_tags(e,v):
                e.set("query_key","id")
                for x in v:
                    ne = etree.SubElement(e, "column")
                    if x != []:
                        for n in x:
                            ne.set(n[0],n[1])
            def _set_tb_tags(e):
                e.set("enable_query","1")
                e.set("enable_show","1")
                e.set("enable_export","1")
                
                
            for k, v in data.items():                
                e = etree.SubElement(parent, k)
                _set_tb_tags(e)
                if type(v) == list and len(v) > 0 :
                    #e1 = etree.SubElement(e, k)
                    _set_col_tags(e,v)
                if type(v) == dict:
                    return __inner(v,e)
                
        
        #print data
        root = etree.Element("root")
        for nd in data:
            np = etree.SubElement(root,nd[0])
            __inner(nd[1],np)
            
        s = etree.tostring(root, pretty_print=True,xml_declaration=True,encoding="UTF-8")
        f = open(self.config,"w")
        f.write(s)
        f.close()
        
    def getxml(self,fn):
        
        root = etree.parse(fn).getroot()
        lines = root.getchildren()
        data = {}
        for line in range(len(lines)):
            if lines[line].attrib !=  {} :#and "class" in lines[line].attrib.keys():
                data[int(lines[line].attrib["id"])] = lines[line]
        return data
        
class request_mysql(DBO):
    def __init__(self,Log,cfg):
        #=======================================================================
        # 初始化变量和方法
        #=======================================================================
        self.data_struct = {}
        self.Update_Flag = False
        self.Log = Log
        self.xml = request_xml(self.Log)
        self.do_test(cfg)
        
    def do_test(self,cfg):    
        DBO.__init__(self, cfg)
        return self.test_conn()
        
               
    def __updatedblist(self):
        return [x[0] for x in self.dosql("show databases;")]
        
    def __updatetblist(self, db):
        return [x[0] for x in self.dosql(["use %s;" % db,"show tables;"])]
        
           
    def __get_tbcolnames(self, db, tb):
        return self.dosql(["show columns from %s.%s;" % (db, tb),])
        
    def read_from_xml_config(self):
        return self.xml.read_cfg()
        
    def create_xml_config(self,db = [("ssdz","fightgame"),]):
        try:
            data = []
            write_data = {}
            for ndb in db:
                dbn = ndb[1]
                np  = ndb[0]
                if not write_data.has_key(dbn):
                    write_data = {dbn:{}}
                for ntb in self.__updatetblist(dbn):
                    tbcols = self.__get_tbcolnames(dbn,ntb)
                    write_data[dbn][ntb] = []
                    for n in tbcols:
                        write_data[dbn][ntb].append([("tag",n[0]),("define",n[1])])
                data.append((np,write_data))
            self.xml.write_cfg(data)
            return True
        except:
            return False
        
    def refresh(self,proj,db,player_id):
        
        def __get_player_id(db,searchkey,player_tb,player_id):
            sql = "select id from %s.%s where " % (db,player_tb)
            ch = re.findall(r"[a-zA-Z]+",player_id)
            try:
                for n in range(len(searchkey)):
                    if searchkey[n] == "id" and ch != []:
                        continue
                    if n != 0:
                        sql = sql + " or "
                    sql = sql + " %s='%s'" % (searchkey[n],player_id)
                
                rd = self.dosql(sql)
                
            except:
                print "can't find player id with input sting [%s]" % player_id
                return None
            if len(rd) > 0 and len(rd[0])>0:
                return rd[0][0]
            else:
                return None
            
        
        
        self.xmlconfig = self.read_from_xml_config()
        config_proj = self.xmlconfig.keys()
        if proj not in config_proj:
            return 1
        proj_cfg_datas = self.xmlconfig[proj]
        
        try:
            player_tb = [x for x in proj_cfg_datas.keys() if x[2:] == "player"][0]
            player_key = proj_cfg_datas[player_tb]["attrib"]["query_key"]
        except:
            return
        if proj == "ssdz":
            player_key = ["name","id","uc_id"]
        elif proj == "tianjie":
            player_key = ["name","id","ucId"]
        player_id = __get_player_id(db,player_key,player_tb,player_id)
        
        
        if player_id == None:
            return
        
        proj_cfg = proj_cfg_datas["attrib"]
        del proj_cfg_datas["attrib"]
        del proj_cfg_datas["database"]
        proj_cfg_enable_query = str(proj_cfg[0][1])

        self.player = {}
        self.player_dec = {}
        
                   
        if proj_cfg_enable_query== "1":
            for tb,tb_cfg_datas in proj_cfg_datas.items():
                self.player[tb] = {}
                self.player_dec[tb] = {}
                query_key = tb_cfg_datas["attrib"]["query_key"]
                if "|" in query_key:
                    tb_sql = ["select * from %s.%s where %s='%s';" % (db,tb,x,player_id) for x in query_key.split("|")]            
                else:
                    tb_sql = ["select * from %s.%s where %s='%s';" % (db,tb,query_key,player_id)]
                self.player_dec[tb] = [x[0] for x in self.__get_tbcolnames(db,tb)] 
                n = 0
                
                for nrow in self.dosql(tb_sql):
                    n += 1
                    self.player[tb]["row_%s" % n] = {}
                    for ncol in range(len(nrow)):
                        self.player[tb]["row_%s" % n][self.player_dec[tb][ncol]] = nrow[ncol]
        return self.player
    
    def SetDatabase(self,db = None):
        if db != None and db.strip() != "": 
            self.database = db.strip()
            
    def SetPlayerQueryName(self, name = None):
        if name != None and name.strip() != "": 
            self.PlayerQeuryName = name.strip()
            
    def SetThreadFlag(self,flag):
        self.Update_Flag = flag

            
    def GetDBList(self):
        return self.dblist
    
    def GetData(self):
        return self.data_struct
    
    def GetDataDes(self):
        return self.data_struct_des
    
    def SetProj(self, proj):
        self.Proj = proj

        

    
    def __refresh_mysql_data(self):
        pass
        #self.ch_db_c.SetItems(dbl)
        #try:
        #    self.ch_db_c.SetSelection(self.database_id)
        #except:
            #self.ch_db_c.SetSelection(0)
        """
        ##导出为xml数据档
        ##导出为xml配置单
        self.r.SetThreadFlag(False)
        data = self.r.GetData()
        print data
        data_des = self.r.GetDataDes()
        print "data_des  is ",data_des 
        player_data = {}
        player_data_cfg = {}
        for k,v in data.items():
            print "k is",k
            print len(v)
            print len(data_des[k])
            player_data[k] = {}#proj
            player_data_cfg[k] = {}
            for k1,v1 in v.items():
                print "k1 is",k1
                if len(k1) >= 1:
                    k1_name = k1[0]
                if data_des[k].has_key(k1_name):
                    print 111111
                print data_des[k]
                des = data_des[k][k1_name]#table
                player_data[k][k1_name] = {}
                player_data_cfg[k][k1_name] = {}
                if v1 == ():
                    continue
                for nidx in range(len(des)):#value
                    player_data[k][k1_name][des[nidx]] = {"enable_show":"1",
                                                      "enable_export":"1"}
                    if len(v1) > 1:
                        kname = des[nidx][0]
                        kdef  = des[nidx][1]
                        for ntag in range(len(v1)):
                            tag = kname+"_line_"+str(ntag)
                            player_data[k][k1_name][tag] = {"value":v1[ntag],
                                                            "col_def":kdef}
                                    
                    
                                
            from dbo import request_xml  
            t = request_xml()
            t.write(player_data)     
           """   
    #def test(self):

        #self.conn_mysql()
        
def test():  
    import log
    b = request_sqlite(log.Log)
    cfg = b.get()[0]
    a = request_mysql(log.Log,cfg)
    #a.create_xml_config([("ssdz","fight_game_h5_backup"),("douhun","killgod3"),("douhun","killgod4")])
    print a.refresh("douhun","killgod3","K_1")#,"t_player","DEAD","player_id")
    print a.refresh("ssdz","fight_game_h5_backup","5357")#,"t_player","DEAD","player_id")
    
#test()
#a.read_from_xml_config()
#a.refresh([("ssdz","fightgame"),("mysql","mysql")])"""

